<template>
  <div class="product-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择商品分类"
          />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="searchForm.brandId" placeholder="请选择品牌" clearable>
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable>
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd">新增商品</el-button>
      <el-button type="danger" :disabled="!selectedProducts.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="productList" border @selection-change="handleSelectionChange" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="商品名称" min-width="180">
        <template #default="scope">
          <div class="product-info">
            <el-image :src="scope.row.image" :preview-src-list="[scope.row.image]" class="product-image" fit="cover" />
            <div class="product-detail">
              <div class="product-name">{{ scope.row.name }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="商品分类" width="120" />
      <el-table-column prop="brandName" label="品牌" width="100" />
      <el-table-column prop="supplierName" label="供应商" width="120" />
      <el-table-column prop="unitName" label="单位" width="80" align="center" />
      <el-table-column prop="originName" label="产地" width="100" />
      <el-table-column prop="color" label="颜色" width="80" align="center" />
      <el-table-column label="价格信息" width="200">
        <template #default="scope">
          <div class="price-info">
            <div>进价：¥{{ scope.row.purchasePrice }}</div>
            <div>售价：¥{{ scope.row.sellingPrice }}</div>
            <div>会员价：¥{{ scope.row.memberPrice }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="总库存" width="80" align="center" />
      <el-table-column label="库存详情" width="100" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleViewStock(scope.row)">查看库存</el-button>
        </template>
      </el-table-column>
      <el-table-column label="日期信息" width="200">
        <template #default="scope">
          <div class="date-info">
            <div>生产日期：{{ scope.row.productionDate }}</div>
            <div>保质期：{{ scope.row.shelfLife }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'info'">
            {{ scope.row.status ? "上架" : "下架" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleStatusChange(scope.row)">
              {{ scope.row.status ? "下架" : "上架" }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 库存详情对话框 -->
    <el-dialog v-model="stockDialogVisible" title="库存详情" width="800px">
      <el-table :data="stockList" border>
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="stock" label="库存数量" width="100" align="center" />
        <el-table-column prop="minStock" label="最小库存" width="100" align="center" />
        <el-table-column prop="maxStock" label="最大库存" width="100" align="center" />
        <el-table-column prop="location" label="库位" width="100" align="center" />
      </el-table>
    </el-dialog>

    <!-- 商品编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加商品' : '修改商品'"
      v-model="dialogVisible"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="productFormData" :rules="rules" label-width="100px" class="product-form">
        <el-form-item label="商品图片">
          <div class="image-upload-container">
            <!-- 主图上传 -->
            <div class="upload-box">
              <div class="upload-title">商品图片</div>
              <div class="upload-subtitle">点击上传主图</div>
              <el-upload
                class="product-image-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
                :on-preview="handlePictureCardPreview"
              >
                <img v-if="productFormData.image" :src="productFormData.image" class="uploaded-image" />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                </div>
              </el-upload>
            </div>

            <!-- 相册图片上传 -->
            <div class="upload-box album-container">
              <div class="upload-title">商品相册</div>
              <div class="upload-subtitle">添加相册图片</div>
              <div class="album-scroll-container">
                <el-upload
                  class="album-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="true"
                  :file-list="productFormData.album"
                  :before-upload="beforeUpload"
                  :on-success="handleAlbumSuccess"
                  :on-remove="handleAlbumRemove"
                  :on-error="handleAlbumError"
                  :on-preview="handlePictureCardPreview"
                  list-type="picture-card"
                >
                  <el-icon class="upload-icon"><Plus /></el-icon>
                </el-upload>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productFormData.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-cascader
                v-model="productFormData.categoryId"
                :options="categoryOptions"
                :props="cascaderProps"
                placeholder="请选择商品分类"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="productFormData.brandId" placeholder="请选择品牌" style="width: 100%">
                <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="productFormData.supplierId" placeholder="请选择供应商" style="width: 100%">
                <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unitId">
              <el-select v-model="productFormData.unitId" placeholder="请选择单位" style="width: 100%">
                <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="originId">
              <el-select v-model="productFormData.originId" placeholder="请选择产地" style="width: 100%">
                <el-option v-for="item in originOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-input v-model="productFormData.color" placeholder="请输入颜色" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select
                multiple
                collapse-tags
                collapse-tags-tooltip
                v-model="productFormData.warehouseId"
                placeholder="请选择仓库"
                style="width: 100%"
              >
                <el-option v-for="item in warehouseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number v-model="productFormData.stock" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="进价" prop="purchasePrice">
              <el-input-number
                v-model="productFormData.purchasePrice"
                :precision="2"
                :step="0.1"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售价" prop="sellingPrice">
              <el-input-number
                v-model="productFormData.sellingPrice"
                :precision="2"
                :step="0.1"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="会员价" prop="memberPrice">
              <el-input-number
                v-model="productFormData.memberPrice"
                :precision="2"
                :step="0.1"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker
                v-model="productFormData.productionDate"
                type="date"
                placeholder="请选择生产日期"
                style="width: 100%"
                format="YYYY年MM月DD日"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保质期" prop="shelfLife">
              <el-date-picker
                v-model="productFormData.shelfLife"
                type="date"
                placeholder="请选择保质期"
                style="width: 100%"
                format="YYYY年MM月DD日"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品描述" prop="description">
          <el-input v-model="productFormData.description" type="textarea" :rows="4" placeholder="请输入商品描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="dialogImagePreview" title="图片预览" width="50%">
      <img :src="dialogImageUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import {
  getProductList,
  getProductStock,
  getProductDetail,
  addProduct,
  updateProduct,
  deleteProduct,
  batchDeleteProducts,
  updateProductStatus,
} from "@/api/product";
import {
  getCategoryList,
  getBrandList,
  getSupplierList,
  getUnitList,
  getOriginList,
  getWarehouseList,
  uploadFile,
  deleteFile,
  deleteFiles,
} from "@/api/common";
import { getToken, setToken } from "@/utils/auth";
import { refresh } from "@/api/auth";
import { getProductListExcel } from "@/api/export";

// 搜索表单数据
const searchForm = reactive({
  name: "",
  categoryId: null,
  brandId: null,
  supplierId: null,
  status: null,
});

// 分页数据
const page = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 表格数据
const productList = ref([]);
const loading = ref(false);
const selectedProducts = ref([]);

// 选项数据
const categoryOptions = ref([]);
const brandOptions = ref([]);
const supplierOptions = ref([]);
const unitOptions = ref([]);
const originOptions = ref([]);
const warehouseOptions = ref([]);

// 级联选择器配置
const cascaderProps = {
  value: "id",
  label: "name",
  children: "children",
  checkStrictly: true,
};

// 库存详情对话框
const stockDialogVisible = ref(false);
const stockList = ref([]);

// 对话框相关
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const dialogImagePreview = ref(false);
const dialogType = ref("add");
const formRef = ref(null);
const submitLoading = ref(false);

// 表单数据
const productFormData = reactive({
  id: undefined,
  name: "",
  categoryId: null,
  brandId: null,
  supplierId: null,
  unitId: null,
  originId: null,
  warehouseId: null,
  color: "",
  image: "",
  album: [],
  purchasePrice: 0,
  sellingPrice: 0,
  memberPrice: 0,
  stock: 0,
  description: "",
  productionDate: null,
  shelfLife: null,
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
  brandId: [{ required: true, message: "请选择品牌", trigger: "change" }],
  supplierId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  unitId: [{ required: true, message: "请选择单位", trigger: "change" }],
  originId: [{ required: true, message: "请选择产地", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  purchasePrice: [{ required: true, message: "请输入进价", trigger: "blur" }],
  sellingPrice: [{ required: true, message: "请输入售价", trigger: "blur" }],
  memberPrice: [{ required: true, message: "请输入会员价", trigger: "blur" }],
};

// 上传相关配置
const uploadUrl = process.env.VUE_APP_API_URL + "/file/upload";
// token响应式数据
const token = ref(getToken());
const uploadHeaders = computed(() => {
  return token.value ? { Authorization: "Bearer " + token.value } : {};
});

// 图片历史记录
const imageHistory = ref("");

// 获取商品列表
const getProducts = async () => {
  loading.value = true;
  try {
    const res = await getProductList({
      ...searchForm,
      categoryId: Array.isArray(searchForm.categoryId)
        ? searchForm.categoryId[searchForm.categoryId.length - 1]
        : searchForm.categoryId,
      current: page.current,
      size: page.size,
    });
    productList.value = res.data.list;
    page.total = res.data.total;
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取选项数据
const getOptions = async () => {
  try {
    const [categories, brands, suppliers, units, origins, warehouses] = await Promise.all([
      getCategoryList(),
      getBrandList(),
      getSupplierList(),
      getUnitList(),
      getOriginList(),
      getWarehouseList(),
    ]);
    categoryOptions.value = categories.data;
    brandOptions.value = brands.data;
    supplierOptions.value = suppliers.data;
    unitOptions.value = units.data;
    originOptions.value = origins.data;
    warehouseOptions.value = warehouses.data;
  } catch (error) {
    console.error("获取选项数据失败:", error);
    ElMessage.error("获取选项数据失败");
  }
};

// 查看库存详情
const handleViewStock = async (row) => {
  try {
    const res = await getProductStock(row.id);
    stockList.value = res.data;
    stockDialogVisible.value = true;
  } catch (error) {
    console.error("获取库存详情失败:", error);
    ElMessage.error("获取库存详情失败");
  }
};

// 搜索
const handleSearch = () => {
  page.current = 1;
  getProducts();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: "",
    categoryId: null,
    brandId: null,
    supplierId: null,
    status: null,
  });
  handleSearch();
};

// 新增商品
const handleAdd = () => {
  dialogType.value = "add";
  imageHistory.value = "";
  dialogVisible.value = true;
};

// 编辑商品
const handleEdit = async (row) => {
  dialogType.value = "edit";
  try {
    const res = await getProductDetail(row.id);
    Object.assign(productFormData, res.data);
    const album = JSON.parse(res.data.album);
    if (album && album.length > 0) {
      productFormData.album = album.map((item) => ({
        // 最后一个/后面
        name: item.substring(item.lastIndexOf("/") + 1),
        url: item,
        status: "success",
        // 最后一个/后面到最后一个.之间
        uid: item.substring(item.lastIndexOf("/") + 1, item.lastIndexOf(".")) || Date.now().toString(),
      }));
    } else {
      productFormData.album = [];
    }
    imageHistory.value = res.data.image;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取商品详情失败:", error);
    ElMessage.error("获取商品详情失败");
  }
};

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
      type: "warning",
    });
    const res = await batchDeleteProducts([row.id]);
    if (res.success) {
      ElMessage.success("删除成功");
      getProducts();
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    console.error("删除商品失败:", error);
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning("请选择要删除的商品");
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除选中的商品吗？", "提示", {
      type: "warning",
    });
    const ids = selectedProducts.value.map((item) => item.id);
    const res = await batchDeleteProducts(ids);
    if (res.success) {
      ElMessage.success("删除成功");
      getProducts();
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    console.error("批量删除商品失败:", error);
  }
};

// 更改商品状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要${row.status ? "下架" : "上架"}该商品吗？`, "提示", {
      type: "warning",
    });
    await updateProductStatus(row.id, row.status ? 0 : 1);
    ElMessage.success("操作成功");
    getProducts();
  } catch (error) {
    console.error("更新商品状态失败:", error);
  }
};

// 导出商品
const handleExport = async () => {
  try {
    await getProductListExcel(searchForm);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出商品失败:", error);
  }
};

// 表格选择项变化
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection;
};

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val;
  getProducts();
};

// 当前页变化
const handleCurrentChange = (val) => {
  page.current = val;
  getProducts();
};

// 图片上传前的处理
const beforeUpload = async (file, fileList) => {
  const isImage = file.type.startsWith("image/");
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt10M) {
    ElMessage.error("图片大小不能超过10MB!");
    return false;
  }
  return true;
};

// 主图片上传前
const beforeImageUpload = async (file, fileList) => {
  if (beforeUpload(file, fileList)) {
    console.log("handleImageChange", file, fileList);
    console.log("historyImageChange", imageHistory.value);
    if (dialogType.value == "add") {
      if (imageHistory.value == "") {
        return true;
      }
      const image = imageHistory.value.substring(imageHistory.value.lastIndexOf("/") + 1);
      return await deleteFile(image).success;
    }
  }
  return true;
};

// 图片上传成功的处理
const handleImageSuccess = (response) => {
  console.log("handleImageSuccess", response);
  if (response.success) {
    productFormData.image = response.data;
    imageHistory.value = response.data;
  } else {
    ElMessage.error("图片上传失败");
  }
};

// 图片上传失败的处理
const handleImageError = async (error, file) => {
  try {
    const refreshResult = await refresh();
    if (refreshResult.success) {
      //更新token
      setToken(refreshResult.data);
      // 更新响应式 token
      token.value = refreshResult.data;
      // 重新上传
      const data = new FormData();
      data.append("file", file.raw || file);
      const uploadResult = await uploadFile(data);
      if (uploadResult.success) {
        productFormData.image = uploadResult.data;
        imageHistory.value = uploadResult.data;
      } else {
        ElMessage.error("图片上传失败");
      }
    } else {
      ElMessage.error("图片上传失败");
    }
  } catch (err) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败");
  }
};
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  console.log("handleSubmit", productFormData);
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    const album = productFormData.album.map((item) => item.url);
    const productFormDataCopy = { ...productFormData };
    productFormDataCopy.album = JSON.stringify(album);
    productFormDataCopy.productionDate = convertToLocalDate(productFormData.productionDate);
    productFormDataCopy.shelfLife = convertToLocalDate(productFormData.shelfLife);
    productFormDataCopy.categoryId =
      // 判断是否为数组
      Array.isArray(productFormData.categoryId)
        ? productFormData.categoryId[productFormData.categoryId.length - 1]
        : productFormData.categoryId;
    console.log("handleSubmit", productFormDataCopy);
    let res = null;
    if (dialogType.value === "add") {
      res = await addProduct(productFormDataCopy);
    } else {
      res = await updateProduct(productFormDataCopy);
    }
    if (res.success) {
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "修改成功");
      getProducts();
      dialogVisible.value = false;
    }
  } catch (error) {
    console.error("提交表单失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitLoading.value = false;
  }
};

// 关闭对话框的处理
const handleDialogClose = () => {
  // 判断是添加还是修改
  if (dialogType.value === "add" && productFormData.image !== "" && productFormData.album.length > 0) {
    // 清空所有图片(只需要最后一个/后的部分)
    const deleteFilesNames = [...productFormData.album.map((item) => item.url), productFormData.image].map((item) =>
      item.substring(item.lastIndexOf("/") + 1)
    );
    deleteFiles(deleteFilesNames);
    imageHistory.value = "";
  }
  formRef.value?.resetFields();
  Object.assign(productFormData, {
    id: undefined,
    name: "",
    categoryId: null,
    brandId: null,
    supplierId: null,
    unitId: null,
    originId: null,
    warehouseId: null,
    color: "",
    image: "",
    album: [],
    purchasePrice: 0,
    sellingPrice: 0,
    memberPrice: 0,
    stock: 0,
    description: "",
    productionDate: null,
    shelfLife: null,
  });
};

// 图片预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogImagePreview.value = true;
};

// 相册图片上传成功
const handleAlbumSuccess = (response, uploadFile) => {
  if (response.success) {
    if (!productFormData.album) {
      productFormData.album = [];
    }
    // 构造符合 Element Plus Upload 组件要求的文件对象
    const fileObj = {
      name: uploadFile.name,
      url: response.data,
      status: "success",
      uid: uploadFile.uid || Date.now().toString(),
    };
    // 使用数组方法触发响应式更新
    productFormData.album = [...productFormData.album, fileObj];
  } else {
    ElMessage.error("图片上传失败");
  }
};

// 相册图片上传失败
const handleAlbumError = async (error, file) => {
  try {
    const refreshResult = await refresh();
    if (refreshResult.success) {
      //更新token
      setToken(refreshResult.data);
      // 更新响应式 token
      token.value = refreshResult.data;
      // 重新上传
      const data = new FormData();
      data.append("file", file.raw || file);
      const uploadResult = await uploadFile(data);
      if (uploadResult.success) {
        console.log("上传成功:", uploadResult);
        // 确保 album 数组已初始化
        if (!productFormData.album) {
          productFormData.album = [];
        }
        // 构造符合 Element Plus Upload 组件要求的文件对象
        const fileObj = {
          name: file.name,
          url: uploadResult.data,
          status: "success",
          uid: file.uid || Date.now().toString(),
        };
        // 使用数组方法触发响应式更新
        productFormData.album = [...productFormData.album, fileObj];
        console.log("相册图片:", productFormData.album);
      } else {
        ElMessage.error("图片上传失败");
      }
    } else {
      ElMessage.error("图片上传失败");
    }
  } catch (err) {
    console.error("相册图片上传失败:", error);
    ElMessage.error("图片上传失败");
  }
};

// 移除相册图片
const handleAlbumRemove = async (uploadFile) => {
  const index = productFormData.album.findIndex((item) => item.url === uploadFile.url);
  if (index !== -1) {
    productFormData.album.splice(index, 1);
  }
  if (dialogType.value === "add") {
    const fileName = uploadFile.url.substring(uploadFile.url.lastIndexOf("/") + 1);
    await deleteFile(fileName);
  }
};

// 将LocalDateTime转换成LocalDate 格式:yyyy-MM-dd
const convertToLocalDate = (dateTime) => {
  if (!dateTime) return null;
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 页面加载时获取数据
onMounted(() => {
  getOptions();
  getProducts();
});
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-weight: 500;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
}

.date-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 20px;
}

.image-upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.upload-box {
  flex: 1;
  text-align: center;
}

.upload-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.upload-subtitle {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
}

.product-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 360px;
  height: 240px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 28px;
  height: 28px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.album-container {
  width: 100%;
  max-width: 800px;
}

.album-scroll-container {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 16px;
  margin-top: 8px;
  height: 210px;
  overflow-y: auto;
}

.album-scroll-container:hover {
  border-color: #409eff;
}

.album-uploader {
  :deep(.el-upload--picture-card) {
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
  }

  :deep(.el-upload-list--picture-card) {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 0;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 148px;
    height: 148px;
    margin: 0;
    position: relative;
    overflow: hidden;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 1;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 2;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item:hover .el-upload-list__item-actions) {
    opacity: 1;
  }

  :deep(.el-upload--picture-card .el-upload-dragger) {
    width: 100%;
    height: 100%;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0 0;
}
</style>
